const {
	Service
} = require('uni-cloud-router')
const uniID = require('uni-id')
const dbHelper = require('db-helper')
const payUtil = require("pay-util")
const {
	wxPubConfig
} = require("config");
const WxPubApi = require("wx-public-api")
const wxPubApi = new WxPubApi()
const tokenUtil = require("token-util");
const moment = require('moment-timezone');
const fs = require('fs');
const path = require('path');
const { WxWithdraw } = require('node-wxpay3');
const wxwithdeaw = new WxWithdraw({
    'partner_key': '409fd902fec330f320662a45d1d97c8f', // key为商户平台设置的密钥key
    'pfx': fs.readFileSync(path.join(__dirname, "../apiclient_cert.p12")),
});
const { v1: uuidv1 } = require('uuid');

module.exports = class RentService extends Service {
	async getRentRecordDetail({
		id
	}) {
		let record = await dbHelper.getById("t3ds-goods-rent-history", id)
		if (!record) {
			throw new Error("记录不存在")
		}
		let store = await dbHelper.getById("t3ds-store", record.storeId)
		record.storeName = store.name
		let order = await dbHelper.getById("t3ds-order", record.orderId)
		record.pledge = order.total_fee
		return record
	}
	async getRentRecords({
		storeId,
		pageNum = 1,
		pageSize = 20,
		keyword
	}) {
		try{
			let store
			if (storeId) {
				store = await dbHelper.getById("t3ds-store", storeId)
				if (!store) {
					throw new Error("门店不存在")
				}
			}
			let user = await dbHelper.getById("uni-id-users", this.ctx.auth.uid)
			if (store && store.uid !== user._id && store.employeeIds.indexOf(user._id) === -1) {
				throw new Error("无权限")
			}
			let isBoss = user.role.some(item => {return item === 'boss'})
			if (!isBoss && !storeId) {
				throw new Error("门店id不能为空")
			}
			let query = {}
			if (storeId) {
				query.storeId = storeId
			}
			if (isBoss && !storeId) {
				let stores = await dbHelper.getList("t3ds-store", {
					uid: user._id
				})
				let storeIds = stores.map(item => {
					return item._id
				})
				query.storeId = this.db.command.in(storeIds)
			}
			if (keyword && /^[0-9]*$/.test(keyword)) {
				let rentMan = await dbHelper.getOne("uni-id-users", {
					id: parseInt(keyword),
					role: 'member'
				})
				if (!rentMan) {
					return {
						total: 0,
						list: []
					}
				}
				query.memberId = rentMan._id
			} else {
				query.memberName = new RegExp(keyword)
			}
				console.log('xxxxxxxxxxxxxxx', query)
			let total = await dbHelper.getCount("t3ds-goods-rent-history", query)
			let res = await this.db.collection("t3ds-goods-rent-history").aggregate()
				.match(query)
				.lookup({
					from: "t3ds-order",
					localField: "orderId",
					foreignField: "_id",
					as: "order"
				})
				.lookup({
					from: "t3ds-store",
					localField: "storeId",
					foreignField: "_id",
					as: "store"
				})
				.lookup({
					from: "uni-id-users",
					localField: "memberId",
					foreignField: "_id",
					as: "member"
				})
				.project({
					memberName: 1,
					rentTime: 1,
					returnTime: 1,
					goodsName: 1,
					count: 1,
					pledge: "$order.total_fee",
					storeName: "$store.name",
					memberId: "$member.id"
				})
				.sort({
					"returnTime": 1,
					"rentTime": -1
				})
				.skip((pageNum - 1) * pageSize)
				.limit(pageSize)
				.end()
			res.data.forEach(item => {
				item.pledge = item.pledge[0]
				item.storeName = item.storeName[0]
				item.memberId = item.memberId[0]
			})
			return {
				total,
				list: res.data
			}
		}catch(e){
			console.error(e)
			throw e
		}
	}
	
	async confirmReturnRent({
		rentRecordId,
		remarks,
		pledgeRefund
	}) {
		let transaction = await this.db.startTransaction()
		try{
			let user = await dbHelper.getById("uni-id-users", this.ctx.auth.uid)
			let rentRecord = await dbHelper.getById("t3ds-goods-rent-history", rentRecordId, transaction)
			if (!rentRecord) {
				await transaction.commit()
				return {
					code: 500,
					msg: "租借记录不存在"
				}
			}
			let store = await dbHelper.getById("t3ds-store", rentRecord.storeId)
			if (store.uid !== user._id && store.employeeIds.indexOf(user._id) === -1) {
				return {
					code: 500,
					msg: "无权限"
				}
			}
			if (rentRecord.returnTime) {
				return {
					code: 500,
					msg: "已确认，无需再次确认"
				}
			}
			
			rentRecord.returnTime = Date.now()
			rentRecord.confirmBy = user.username
			rentRecord.pledgeRefund = pledgeRefund
			rentRecord.remarks = remarks
			await dbHelper.update("t3ds-goods-rent-history", rentRecord, transaction)
			
			// 还原库存
			await dbHelper.update("t3ds-goods-rent", {
				_id: rentRecord.goodsId,
				stock: this.db.command.inc(rentRecord.count)
			}, transaction)
			
			// 更新订单状态，退押金是7即退款中，不退是5即订单完成
			await dbHelper.update("t3ds-order", {
				_id: rentRecord.orderId,
				status: pledgeRefund ? 7 : 5
			}, transaction)
			
			if (pledgeRefund) {
				let order = await dbHelper.getById("t3ds-order", rentRecord.orderId)
				let uniPayInstance = payUtil.getPayInstance(order.pay_type, order.platform);
				let res = await uniPayInstance.refund({
					outTradeNo: order._id,
					outRefundNo: order._id,
					totalFee: Math.round(order.payment_fee), // 订单总金额，支付宝可不填此项
					refundFee: Math.round(order.payment_fee), // 退款总金额
				})
			}
			
			await transaction.commit()
			return {
				code: 200,
				result: rentRecord
			}
		}catch(e){
			console.error(e)
			if (transaction) {
				await transaction.rollback()
			}
			return {
				code: 500,
				msg: e.message
			}
		}
	}
}
